/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */
package com.jav;

import com.jav.data.InvMovilData;
import com.jav.per.PersisCaptura;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.M3G;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class ExportForm extends Form {

    private Button bt_exp;
    private Button bt_borrar;
    private Button bt_configuracion;
    private static final VentanaEspera waiting = new VentanaEspera("EXPORTANDO...");
    private Image imgError;
    private Resources res = null;

    public ExportForm() {
        super("DATOS");
        setLayout(new BorderLayout());
        try {
            if (M3G.isM3GSupported()) {
                setTransitionInAnimator(Transition3D.createStaticRotation(500, true));
                setTransitionOutAnimator(Transition3D.createStaticRotation(500, false));
            } else {
                setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500));
                setTransitionOutAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500));
            }
        } catch (Exception e) { }


        res = Datos.getInstance().getRes();


        addCommand(new Command("Atrás", res.getImage("bck.png")) {

            public void actionPerformed(ActionEvent evt) {
                InvMovilMidlet.getMainForm().show();
            }
        });

        bt_exp = new Button("EXPORTAR");
        bt_exp.setAlignment(CENTER);

        bt_exp.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {

                    public void run() {
                        waiting.showModeless();
                        try {
                            guardarPedido(leerRsCaptura());
                        } catch (Exception e) {
                            e.printStackTrace();
                            Command okCommand = new Command("OK");
                            imgError = res.getImage("cancel.png");
                            Dialog.show("Falló!", "Error al exportar los datos:\n" + e.getMessage(),
                                    okCommand, new Command[]{okCommand}, Dialog.TYPE_ERROR, imgError, 0, null);
                        } finally {
                            waiting.dispose();
                        }

                    }
                }).start();
            }
        });

        bt_borrar = new Button("BORRAR DATOS");
        bt_borrar.setAlignment(CENTER);
        bt_borrar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (Dialog.show("¿?", "ESTA SEGURO DE ELIMINAR LOS DATOS GUARDADOS EN LA APLICACIÓN?", "SI", "NO")) {
                    borrarRecords();
                }
            }
        });


        bt_configuracion = new Button("CONFIGURACION");
        bt_configuracion.setAlignment(CENTER);

        bt_configuracion.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                String pass = LoginDialog.ShowInputBox("Login", "Clave:");
                if(pass == null){
                    return;
                }
 else if(!pass.equals(InvMovilData.PASSWORD_CONF)) {
                    Command[] comando = new Command[]{new Command("OK")};
                    Dialog.show("Error", new Label("Login invalido!!"), comando);
                } else {

                    new Thread(new Runnable() {

                        Form forma;

                        public void run() {
                            waiting.showModeless();
                            forma = new SetupForm();
                            waiting.dispose();
                            forma.show();

                        }
                    }).start();

                }

            }
        });

        Container centrado = new Container();
        centrado.setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        centrado.addComponent(bt_exp);
        centrado.addComponent(new Label(""));
        centrado.addComponent(bt_configuracion);
        centrado.addComponent(new Label(""));
        centrado.addComponent(bt_borrar);

        addComponent(BorderLayout.CENTER, centrado);


    }

    /**
     * Lee los datos del RecordStored PEDIDOS
     */
    private StringBuffer leerRsCaptura() throws Exception {
        Persistencia p = null;
        StringBuffer datPed = new StringBuffer("");
        try {
            p = new Persistencia(InvMovilData.PERS_CAPTURA);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                PersisCaptura pd = new PersisCaptura();
                pd.resurrect(re.nextRecord());
                datPed.append(pd.toString() + InvMovilData.ENTER);
            }
        } finally {
            p.close();
        }
        return datPed;

    }



    private void guardarPedido(final StringBuffer datos) throws IOException {
        escribirArchivo((InvMovilData.ISENCAB ? InvMovilData.CAB_CAPTURA : "") + datos.toString(), getRuta() + InvMovilData.NOM_ARC_INVENTARIO);
    }

    private void escribirArchivo(String datos, String ruta) throws IOException {
        FileConnection fc = null;
        java.io.OutputStream os = null;
        try {
            fc = (FileConnection) Connector.open(ruta);
            if (!fc.exists()) {
                fc.create();
            } else {
                fc.truncate(0);
            }
            os = fc.openOutputStream();
            os.write(datos.getBytes());
        } finally {
            if (fc != null) {
                fc.close();
            }
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }



    private void borrarRecords() {
        try {
            //borrar record Stored de capturas
            RecordStore.deleteRecordStore(InvMovilData.PERS_CAPTURA);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            //borrar record Stored del consecutivo de pedido
            RecordStore.deleteRecordStore(InvMovilData.PERS_MAXCONSEC);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected String getRuta() {
        Persistencia p = null;
        String ruta = "";
        try {
            p = new Persistencia(InvMovilData.PERS_RUTA);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                ByteArrayInputStream bin = new ByteArrayInputStream(re.nextRecord());
                DataInputStream din = new DataInputStream(bin);
                ruta = din.readUTF();
                bin.close();
                din.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (p != null) {
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return ruta;
    }

  
}
